// Copyright (c) 2025, qiushike and contributors
// For license information, please see license.txt

frappe.ui.form.on("Wip Transfer", {
	refresh(frm) {
		// 设置供应商字段的过滤条件
		frm.set_query("from_supplier", function() {
			return {
				query: "light_mes.light_mes.doctype.wip_transfer.wip_transfer.get_subcontracting_suppliers",
				filters: {
					"company": frm.doc.company
				}
			};
		});

		frm.set_query("to_supplier", function() {
			return {
				query: "light_mes.light_mes.doctype.wip_transfer.wip_transfer.get_subcontracting_suppliers",
				filters: {
					"company": frm.doc.company
				}
			};
		});

		// 设置明细表中加工单的过滤条件
		frm.set_query("job_card", "wip_transfer_item", function(doc, cdt, cdn) {
			let row = locals[cdt][cdn];
			let filters = {
				'docstatus': 0,  // 草稿状态
				'company': doc.company,
			};
			
			// 如果选择了工单，则限制工单
			if (row.work_order) {
				filters['work_order'] = row.work_order;
			}
			
			// 如果是委外发料或入库，则限制供应商
			if (doc.type === 'Send to Supplier' || doc.type === 'Receive from Supplier') {
				filters['custom_supplier'] = doc.from_supplier;
			}
			
			// 添加车间过滤条件
			filters['custom_plant_floor'] = doc.plant_floor;
			
			return {
				filters: filters
			};
		});

		// 更新按钮显示
		frm.trigger('update_buttons');
		
		// 根据类型控制字段的只读状态
		frm.trigger('toggle_fields_editable');
	},
	
	// 当类型变更时，触发按钮显示更新和字段显示控制
	type: function(frm) {
		frm.trigger('update_buttons');
		frm.trigger('toggle_fields_editable');
	},
	
	// 更新按钮显示
	update_buttons: function(frm) {
		// 清除所有自定义按钮
		frm.clear_custom_buttons();
		
		// 添加"选择待发料数据"按钮 - 当类型为委外发料且文档为草稿状态时显示
		if ((frm.doc.docstatus === 0) && (frm.doc.type === "Send to Supplier")) {
			frm.add_custom_button(__('Select Subcontracting Data'), function() {
				// 校验供应商是否已填写
				if (!frm.doc.from_supplier) {
					frappe.msgprint({
						title: __('Supplier Required'),
						indicator: 'red',
						message: __('Please select a supplier first before selecting subcontracting data.')
					});
					return;
				}
				
				// 如果已填写供应商，则显示对话框
				show_subcontracting_operations_dialog(frm);
			});
		}
		
		// 只有已提交的委外发料和委外入库单据才显示退货按钮
		if (frm.doc.docstatus === 1 && 
			(frm.doc.type === "Send to Supplier" || frm.doc.type === "Receive from Supplier")) {
			
			frm.add_custom_button(__('Make Return'), function() {
				frappe.model.open_mapped_doc({
					method: "light_mes.light_mes.doctype.wip_transfer.wip_transfer.make_wip_transfer_return",
					frm: frm
				});
			}, __('Create'));
		}
	},
	
	// 控制字段的只读状态
	toggle_fields_editable: function(frm) {
		// 委外发料不需要编辑废品数量和入库数量
		const is_send_to_supplier = frm.doc.type === 'Send to Supplier';
		// 退货单不允许编辑废品数量
		const is_return = frm.doc.is_return;
		
		// 设置废品数量字段的只读属性
		frm.fields_dict.wip_transfer_item.grid.update_docfield_property(
			'scrap_qty', 
			'read_only', 
			is_send_to_supplier || is_return
		);
		
		// 如果是委外发料或退货单，将废品数量设为0
		if (is_send_to_supplier || is_return) {
			(frm.doc.wip_transfer_item || []).forEach(item => {
				if (item.scrap_qty) {
					frappe.model.set_value(item.doctype, item.name, 'scrap_qty', 0);
				}
			});
		}
		
		// 刷新字段显示
		frm.refresh_field('wip_transfer_item');
	}
});

frappe.ui.form.on('Wip Transfer Item', {
	// 当工单变化时，清空加工单
	work_order: function(frm, cdt, cdn) {
		let row = locals[cdt][cdn];
		if (row.work_order) {
			frappe.model.set_value(cdt, cdn, 'job_card', '');
		}
	},
	
	// 当数量变化时，自动计算入库数量
	qty: function(frm, cdt, cdn) {
		calculate_in_qty(frm, cdt, cdn);
	},
	
	// 当报废数量变化时，自动计算入库数量
	scrap_qty: function(frm, cdt, cdn) {
		calculate_in_qty(frm, cdt, cdn);
	}
});

// 计算入库数量的函数
function calculate_in_qty(frm, cdt, cdn) {
	let row = locals[cdt][cdn];
	let qty = flt(row.qty) || 0;
	let scrap_qty = flt(row.scrap_qty) || 0;
	let total_qty = qty + scrap_qty;
	
	frappe.model.set_value(cdt, cdn, 'total_qty', total_qty);
}

// 自定义对话框函数
function show_subcontracting_operations_dialog(frm) {
	// 如果类型尚未设置，自动设置为"委外发料"
	if (!frm.doc.type) {
		frm.set_value('type', 'Send to Supplier');
	}
	
	// 创建对话框
	const d = new frappe.ui.Dialog({
		title: __("Select Subcontracting Data"),
		fields: [
			{
				fieldtype: 'Section Break',
				label: __('Filters')
			},
			{
				fieldtype: 'Column Break'
			},
			{
				fieldtype: 'Link',
				label: __('Supplier'),
				fieldname: 'from_supplier',
				options: 'Supplier',
				default: frm.doc.from_supplier || '',
				read_only: 1,  // 设置为只读
				get_query: function() {
					return {
						query: "light_mes.light_mes.doctype.wip_transfer.wip_transfer.get_subcontracting_suppliers",
						filters: {
							"company": frm.doc.company
						}
					};
				}
			},
			{
				fieldtype: 'Column Break'
			},
			{
				fieldtype: 'Link',
				label: __('Plant Floor'),
				fieldname: 'plant_floor',
				options: 'Plant Floor',
				default: frm.doc.plant_floor || ''
			},
			{
				fieldtype: 'Column Break'
			},
			{
				fieldtype: 'DateRange',
				label: __('Date Range'),
				fieldname: 'date_range'
			},
			{
				fieldtype: 'Section Break'
			},
			{
				fieldtype: 'MultiSelectList',
				label: __('Work Orders'),
				fieldname: 'work_orders',
				get_data: function(txt) {
					return frappe.db.get_link_options('Work Order', txt, {
						docstatus: 1,
						company: frm.doc.company
					});
				},
				description: __('Select multiple work orders')
			},
			{
				fieldtype: 'Section Break'
			},
			{
				fieldtype: 'Data',
				label: __('Search'),
				fieldname: 'search',
				description: __('Search by Work Order, Item, Operation')
			},
			{
				fieldtype: 'HTML',
				fieldname: 'results_area'
			}
		],
		primary_action_label: __('Add Items'),
		primary_action: function() {
			// 获取选中的项目
			const selected_items = [];
			d.$wrapper.find('input[type=checkbox]:checked').each(function() {
				if ($(this).attr('id') !== 'select-all') {
					const item = JSON.parse($(this).attr('data-item'));
					selected_items.push(item);
				}
			});
			
			if (selected_items.length === 0) {
				frappe.msgprint(__('Please select at least one item'));
				return;
			}
			
			// 添加项目到表单 - 传递对话框对象
			add_items_to_form(frm, selected_items, d);
			
			// 关闭对话框
			d.hide();
		}
	});
	
	// 设置对话框宽度
	d.$wrapper.find('.modal-dialog').css('max-width', '90%');
	d.$wrapper.find('.modal-dialog').css('width', '1500px');
	
	// 显示对话框
	d.show();
	
	// 添加搜索框事件处理
	d.fields_dict.search.df.onchange = function() {
		search_items();
	};
	
	// 初始搜索
	search_items();
	
	// 添加延迟搜索功能
	let search_timeout = null;
	d.$wrapper.find('input[data-fieldname="search"]').on('input', function() {
		clearTimeout(search_timeout);
		search_timeout = setTimeout(function() {
			search_items();
		}, 300);
	});
	
	// 添加过滤器变更事件处理 - 移除供应商字段，因为它是只读的
	['work_orders', 'plant_floor', 'date_range'].forEach(function(field) {
		d.fields_dict[field].df.onchange = function() {
			search_items();
		};
	});
	
	// 搜索函数
	function search_items() {
		// 构建过滤条件
		let filters = {
			company: frm.doc.company,
			from_supplier: frm.doc.from_supplier  // 始终使用表单中的供应商
		};
		
		// 添加车间过滤
		if (d.get_value('plant_floor')) {
			filters.plant_floor = d.get_value('plant_floor');
		}
		
		// 添加日期范围过滤
		if (d.get_value('date_range')) {
			let date_range = d.get_value('date_range');
			if (date_range && date_range.length === 2) {
				filters.date_from = date_range[0];
				filters.date_to = date_range[1];
			}
		}
		
		// 获取工单过滤条件
		let work_orders = d.get_value('work_orders') || [];
		
		// 执行查询
		frappe.call({
			method: 'light_mes.light_mes.doctype.wip_transfer.wip_transfer.get_subcontracting_operations_for_sending',
			args: {
				doctype: "Wip Transfer",
				txt: d.get_value('search') || "",
				searchfield: "name",
				filters: filters,
				work_orders: work_orders,
				as_dict: 1
			},
			callback: function(r) {
				if (r.message && r.message.length > 0) {
					// 构建表格HTML
					let html = `
					<div style="max-height: 500px; overflow-y: auto; margin-top: 15px;">
						<table class="table table-bordered table-hover" style="cursor: pointer; width: 100%;">
							<thead>
								<tr class="active">
									<th style="width: 30px; text-align: center;">
										<input type="checkbox" id="select-all">
									</th>
									<th style="width: 10%; text-align: left; vertical-align: middle;">${__('Work Order')}</th>
									<th style="width: 10%; text-align: left; vertical-align: middle;">${__('Production Item')}</th>
									<th style="width: 12%; text-align: left; vertical-align: middle;">${__('Item Name')}</th>
									<th style="width: 10%; text-align: center; vertical-align: middle;">${__('Current Operation')}</th>
									<th style="width: 10%; text-align: center; vertical-align: middle;">${__('Previous Operation')}</th>
									<th style="width: 8%; text-align: right; vertical-align: middle;">${__('Received Qty')}</th>
									<th style="width: 8%; text-align: right; vertical-align: middle;">${__('Sent Qty')}</th>
									<th style="width: 8%; text-align: right; vertical-align: middle;">${__('Available Qty')}</th>
									<th style="width: 8%; text-align: left; vertical-align: middle;">${__('Supplier')}</th>
									<th style="width: 8%; text-align: left; vertical-align: middle;">${__('Plant Floor')}</th>
									<th style="width: 8%; text-align: center; vertical-align: middle;">${__('Date')}</th>
								</tr>
							</thead>
							<tbody>
					`;
					
					// 过滤工单
					let filtered_items = r.message;
					if (work_orders && work_orders.length) {
						filtered_items = r.message.filter(item => 
							work_orders.includes(item.work_order)
						);
					}
					
					filtered_items.forEach(function(item) {
						const item_json = JSON.stringify(item);
						html += `
							<tr>
								<td style="text-align: center;"><input type="checkbox" data-item='${item_json}'></td>
								<td style="overflow: hidden; text-overflow: ellipsis; white-space: nowrap; text-align: left;">${item.work_order || ''}</td>
								<td style="overflow: hidden; text-overflow: ellipsis; white-space: nowrap; text-align: left;">${item.production_item || ''}</td>
								<td style="overflow: hidden; text-overflow: ellipsis; white-space: nowrap; text-align: left;">${item.item_name || ''}</td>
								<td style="overflow: hidden; text-overflow: ellipsis; white-space: nowrap; text-align: center;">${item.operation || ''}</td>
								<td style="overflow: hidden; text-overflow: ellipsis; white-space: nowrap; text-align: center;">${item.previous_operation || ''}</td>
								<td style="text-align: right;">${frappe.format(item.received_qty || 0, {fieldtype: 'Float'})}</td>
								<td style="text-align: right;">${frappe.format(item.sent_qty || 0, {fieldtype: 'Float'})}</td>
								<td style="text-align: right;">${frappe.format(item.available_qty || 0, {fieldtype: 'Float'})}</td>
								<td style="overflow: hidden; text-overflow: ellipsis; white-space: nowrap; text-align: left;">${item.supplier || ''}</td>
								<td style="overflow: hidden; text-overflow: ellipsis; white-space: nowrap; text-align: left;">${item.plant_floor || ''}</td>
								<td style="text-align: center;">${item.date ? frappe.datetime.str_to_user(item.date) : ''}</td>
							</tr>
						`;
					});
					
					html += `
							</tbody>
						</table>
					</div>
					`;
					
					d.fields_dict.results_area.$wrapper.html(html);
					
					// 添加全选功能
					d.$wrapper.find('#select-all').on('click', function() {
						const checked = $(this).prop('checked');
						d.$wrapper.find('input[type=checkbox]').prop('checked', checked);
					});
					
					// 添加行点击选择功能
					d.$wrapper.find('tbody tr').on('click', function(e) {
						if (e.target.type !== 'checkbox') {
							const checkbox = $(this).find('input[type=checkbox]');
							checkbox.prop('checked', !checkbox.prop('checked'));
						}
					});
					
					// 添加鼠标悬停显示完整内容的功能
					d.$wrapper.find('td[style*="overflow: hidden"]').each(function() {
						$(this).attr('title', $(this).text());
					});
				} else {
					d.fields_dict.results_area.$wrapper.html(`
						<div class="text-center" style="margin-top: 20px;">
							<p>${__('No items found')}</p>
						</div>
					`);
				}
			}
		});
	}
}

// 添加项目到表单
function add_items_to_form(frm, selected_items, dialog) {
	// 清空现有项目
	frm.clear_table('wip_transfer_item');
	
	// 添加选中的项目
	selected_items.forEach(function(item) {
		const child = frm.add_child('wip_transfer_item');
		
		// 设置基本字段
		child.work_order = item.work_order;
		child.operation_id = item.operation_id;  // 使用委外工序的ID
		child.operation = item.operation;  // 使用委外工序名称
		child.qty = item.available_qty;
		child.scrap_qty = 0;
		child.total_qty = item.available_qty;
		
		// 设置加工单字段 - 使用委外工序的加工单
		if (item.job_card) {
			child.job_card = item.job_card;
		}
	});
	
	// 刷新表格
	frm.refresh_field('wip_transfer_item');
		
	// 设置车间 - 优先使用对话框中选择的车间
	if (dialog && dialog.get_value('plant_floor')) {
		frm.set_value('plant_floor', dialog.get_value('plant_floor'));
	}
	// 如果对话框中没有选择车间，则使用第一个选中项目的车间
	// else if (!frm.doc.plant_floor && selected_items.length > 0 && selected_items[0].plant_floor) {
	// 	frm.set_value('plant_floor', selected_items[0].plant_floor);
	// }
}

